package com.xing.photo.funcation;

import com.xing.photo.bean.PhotoUser;
import com.xing.photo.dao.UserDao;
import com.xing.photo.util.StaticUtil;
import com.xing.photo.util.VarConfig;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: xingzhe
 * Date: 2015/3/3
 * Time: 11:46
 */
public class Single {
    private static final ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
    VarConfig config = (VarConfig) ac.getBean("config");
    UserDao userDao = (UserDao) ac.getBean("userDao");
    public static Set<Long> uids = new HashSet<Long>();
    private static Logger photoPath = LoggerFactory.getLogger("photoPath");

    public static void main(String[] args) throws Exception {
//        Single single = new Single();
//        single.getSingle(6);
        readFileByLines("e:/education_wid.csv");
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet();
        String result = "";
        for (Long uid : uids) {
            URI uri = new URI("http://59.151.73.13:8080/platform-c-2.1.2/resume/education?wid=" + uid);
            get.setURI(uri);
            CloseableHttpResponse response = httpClient.execute(get);
            HttpEntity re = response.getEntity();
            if (re != null) {
                result = EntityUtils.toString(re, "utf-8");
            }
            System.out.println(result);
            photoPath.info(result);
            Thread.sleep(100);
        }
    }

    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String tempString;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                uids.add(Long.parseLong(tempString));
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }


    private void getSingle(int id) throws IOException {
        PhotoUser user = userDao.getUser(id);
        String content = getContent(getUri(user, config.getPageBegin()));
        ObjectMapper mapper = new ObjectMapper();
        JsonNode resultNode = mapper.readTree(content);
        int total = resultNode.get("data").get("total").asInt();
        batchImg(user, total);
    }

    private void batchImg(PhotoUser user, int total) throws IOException {
        int pageCount = total / config.getCount() + 1;
        for (int i = 1; i < pageCount; i++) {
            URI uri = getUri(user, i);
            String content = getContent(uri);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode resultNode = mapper.readTree(content);
            JsonNode dataNode = resultNode.get("data").get("photo_list");
            for (int j = 0; j < dataNode.size(); j++) {
                System.out.println("http://ww3.sinaimg.cn/large/" + dataNode.get(j).get("pic_name").asText());
                saveImg2("http://ww3.sinaimg.cn/large/" + dataNode.get(j).get("pic_name").asText(), dataNode.get(j).get("pic_name").asText(), user.getName());
            }
        }
    }

    private void saveImg2(String img, String picName, String userName) {
        URI uri = null;
        try {
            uri = new URI(img);
            File file = new File("E:/weibo_photo/" + userName + "/");
            if (!file.exists()) {
                file.mkdir();
            }
            HttpGet httpGet = new HttpGet(uri);
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            InputStream in = response.getEntity().getContent();
            byte[] by = new byte[1024];
            int len = -1;
            FileOutputStream fos = new FileOutputStream(new File("E:/weibo_photo/" + userName + "/" + picName));
            while (-1 != (len = in.read(by))) {
                fos.write(by, 0, len);
            }
            fos.flush();
            in.close();
            fos.close();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveImg(String img, String picName, String userName) {
        InputStream is = null;
        OutputStream os = null;
        URL url = null;
        HttpURLConnection con = null;
        File file = new File("E:/weibo_photo/" + userName + "/");
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            url = new URL(img);
            con = (HttpURLConnection) url.openConnection();
            // 设置连接超时
            con.setConnectTimeout(100 * 1000);
            // 设置读取超时
            con.setReadTimeout(100 * 1000);
            is = new BufferedInputStream(con.getInputStream());
            os = new BufferedOutputStream(new FileOutputStream(new File("E:/weibo_photo/" + userName + "/" + picName)));
            byte[] b = new byte[1024];
            int length = 0;
            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }
            os.flush();
            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private URI getUri(PhotoUser user, int pageBegin) {
        URI uri = null;
        try {
            uri = new URIBuilder().setScheme(config.getUriScheme()).setHost(config.getHost()).setPath(config.getPath())
                    .setParameter("uid", user.getUid() + "")
                    .setParameter("album_id", user.getAlbumId() + "")
                    .setParameter("count", config.getCount() + "")
                    .setParameter("page", pageBegin + "")
                    .setParameter("type", config.getType() + "").build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return uri;
    }

    private String getContent(URI uri) {
        String result = null;
        try {
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Cookie", StaticUtil.cookies);
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity re = response.getEntity();
            result = EntityUtils.toString(re, config.getCharset());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
